﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lifang.Dao;
using Lifang.Entites;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Specialized;
using Lifang.Enum;

namespace Lifang.API.Controllers
{
    [Route("api/Category")]
    public class CategoryController : BaseController
    {
        [HttpGet("ValidList")]
        public JsonResult ValidList()
        {
            var dp = Pager;
            dp.OrderField = "  SortNum ASC  ";
            var nvc = new NameValueCollection();
            if (Request.Query != null)
            {
                foreach (var key in Request.Query.Keys)
                {
                    nvc.Add(key, Request.Query[key]);
                }
            }
            var list = new CommonQuery().SelectViewPagerByKey<DP_Category>("CategoryView", nvc, dp);
            Pager = dp;
            return Json(list);
        }

        [HttpGet("QueryByLevel")]
        public JsonResult QueryByLevel(int level)
        {
            var nvc = new NameValueCollection();
            nvc.Add(DP_CategoryValue.Level, level.ToString());
            nvc.Add(DP_CategoryValue.DataFlag, DataFlagEnum.Valid.ToString("d"));
            var list = new DapperHelper().SelectList<DP_Category>(nvc, new SqlNote("wmg", "查询栏目列表"));

            return Json(list);
        }


        [HttpGet("Tree")]
        public JsonResult Tree()
        {
            var nvc = new NameValueCollection();
            nvc.Add(DP_CategoryValue.DataFlag, DataFlagEnum.Valid.ToString("d"));
            var list = new DapperHelper().SelectList<DP_Category>(nvc, new SqlNote("wmg", "查询栏目列表"));

            var oneList = (from item in list
                           where item.Level == 0
                           select new CategoryTree()
                           {
                               Id = item.Id,
                               Name = item.Name,
                               PId = item.PId
                           }).ToList();


            foreach (var item in oneList)
            {
                item.Children = new List<CategoryTree>();
                item.Children = (from it in list
                                 where it.PId == item.Id && item.Id != it.Id
                                 select new CategoryTree()
                                 {
                                     Id = it.Id,
                                     Name = it.Name,
                                     PId = it.PId,
                                     Children = new List<CategoryTree>()
                                 }).ToList();
            }
            return Json(oneList);
        }
    }
}
